import axios from 'axios'
import router from '@/router'
import { NO_PERMISION_CODE, OK_CODE } from '@/app/keys'

const request = axios.create({
  // baseURL: import.meta.env.VITE_API_URL,
  timeout: 10000,
})

// 请求拦截器
request.interceptors.request.use(config => {
  // const user = JSON.parse(localStorage.getItem(KEY_USER_ID)) || {}
  // if (user.token) {
  //   config.headers['Authorization'] = `Bearer ${user.token}`
  // }
  config.url = import.meta.env.VITE_API_URL + config.url
  return config
})

// 响应拦截器
request.interceptors.response.use(res => {
  const { code, msg } = res.data || {}
  if (code !== OK_CODE) {
    return Promise.reject(msg)
  }
  if (code === NO_PERMISION_CODE) {
    router.push({ name: 'Login' })
    return Promise.reject(msg)
  }
  return Promise.resolve(res)
})

export default request
